package cn.vivi.test.downloadprovider;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.vivi.test.downloadprovider.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import cn.vivi35.downloadprovider.app.DownloadManager;
import cn.vivi35.downloadprovider.app.DownloadManagerFile;
import cn.vivi35.downloadprovider.app.DownloadManagerHelper;

public class MainActivity extends AppCompatActivity {
    private TextView tvStorePosition;
    private EditText etFilename;

    private final static String SUFFIX = ".apk";

    private final static String URI_FILE = "http://gdown.baidu.com/data/wisegame/246aa4283544e9e3/baidushoujizhushou_16786281.apk";
    private FileListFragment mLoadListFrag;

    // 下次要下载的文件名
//    private String mNextDownFilename = getRandomName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvStorePosition = (TextView) findViewById(R.id.tvStorePosition);
        etFilename = (EditText) findViewById(R.id.etFilename);
        etFilename.setText(getRandomName());

        File file = new File(FileManager.getImageCachePath(this));
        tvStorePosition.setText(tvStorePosition.getText().toString() + file.toString());

        Button btnDownFile = (Button) findViewById(R.id.btnDownFile);
        btnDownFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadFile(MainActivity.this);
            }
        });

        mLoadListFrag = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fragLoadList);

    }

    private static String getRandomName() {
        String dateRandom = "" + Calendar.getInstance().getTimeInMillis();
        String name = "a" + dateRandom.substring(0, dateRandom.length());
        return name + SUFFIX;
    }


    void loadFile(Context context) {
        Uri srcUri = Uri.parse(URI_FILE);
        DownloadManager.Request request = new DownloadManager.Request(srcUri);

        try {
            File file = new File(FileManager.getApksDownloadPath());
            Uri desUri = Uri.withAppendedPath(Uri.fromFile(file), etFilename.getText().toString());
            //Set next download file name
            etFilename.setText(getRandomName());

            request.setDestinationUri(desUri);
            DownloadManager downloadManager = new DownloadManager(context.getContentResolver(), context.getPackageName());
            downloadManager.enqueue(request);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }


    private void unregisterReceiver() {
        if (mDownloadReceiver != null) {
            unregisterReceiver(mDownloadReceiver);
        }
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_PAUSED);
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_FAILED);
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_RUNNING_START);
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_PROGRESS_UPDATE);
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_PENDING);
        registerReceiver(mDownloadReceiver, intentFilter);
    }

    private BroadcastReceiver mDownloadReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent
                    .getAction())) {
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
                String filename = intent.getStringExtra(DownloadManager.EXTRA_DOWNLOAD_FILENAME);

                Log.i("vivi", "ACTION_DOWNLOAD_COMPLETE : id == " + id + "  filename == " + filename);
                updateListView(id);

            } else if (DownloadManager.ACTION_DOWNLOAD_PAUSED.equals(intent.getAction())) {
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
                String filename = intent.getStringExtra(DownloadManager.EXTRA_DOWNLOAD_FILENAME);
                long reasonCode = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_REASON, DownloadManager.PAUSED_UNKNOWN);
                Log.i("vivi", "action_paused code: " + reasonCode);
                updateListView(id);

            } else if (DownloadManager.ACTION_DOWNLOAD_FAILED.equals(intent.getAction())) {
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
                Log.i("vivi", "ACTION_DOWNLOAD_FAILED");
                long errorCode = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_REASON, -1);
                Log.i("vivi", "action_error code: " + errorCode);
                updateListView(id);

            } else if (DownloadManager.ACTION_DOWNLOAD_RUNNING_START.equals(intent.getAction())) {
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
                String filename = intent.getStringExtra(DownloadManager.EXTRA_DOWNLOAD_FILENAME);
                Log.i("vivi", "ACTION_DOWNLOAD_RUNNING_START : id == " + id + "  filename == " + filename);
                updateListView(id);

            } else if (DownloadManager.ACTION_DOWNLOAD_PROGRESS_UPDATE.equals(intent.getAction())) {
                long id = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
                String filename = intent.getStringExtra(DownloadManager.EXTRA_DOWNLOAD_FILENAME);
//                Log.i("vivi", "ACTION_DOWNLOAD_PROGRESS_UPDATE : id == " + id + "  filename == " + filename);
                updateListView(id);

            } else if (DownloadManager.ACTION_DOWNLOAD_PENDING.equals(intent.getAction())) {
                long id = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
                String filename = intent.getStringExtra(DownloadManager.EXTRA_DOWNLOAD_FILENAME);
                long status = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_REASON, -1L);
                Log.i("vivi", "ACTION_DOWNLOAD_PENDING : id == " + id + "  filename == " + filename+ "  statue  == " + status);
                updateListView(id);

            }

        }
    };

    private void updateListView(long id) {
        DownloadManagerFile loadingFile = DownloadManagerHelper.findFileById(MainActivity.this, id);
        mLoadListFrag.updateFile(loadingFile);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

  /*  @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver();
    }*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }
}
